package com.xxxx.server.controller;


import com.xxxx.server.pojo.Menu;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IMenuRoleService;
import com.xxxx.server.service.IMenuService;
import com.xxxx.server.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;

    @Autowired
    private IMenuRoleService menuRoleService;
    @ApiOperation(value = "查询所有的角色")
    @GetMapping("/")
    public List<Role> getAll(){
        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/role")
    public RespBean save(@RequestBody Role role){
        roleService.save(role);
        return RespBean.success("添加成功");
    }

    @ApiOperation(value = "可访问所有资源")
    @GetMapping("/menus")
    public List<Menu> getMenu(){
        return menuService.getMenusWithRoles();
    }

    @ApiOperation(value = "角色的可访问资源")
    @GetMapping("/mid/{id}")
    public List<Integer> getMenu(@PathVariable("id") int id){
        List<Menu> menus = menuService.getmenuByRoleId(id);
        List<Integer> ids = menus.stream().map(menu -> menu.getId()).collect(Collectors.toList());
        return ids;
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{id}")
    public RespBean delete(@PathVariable("id") int id){
        roleService.removeById(id);
        return RespBean.success("删除成功");
    }

    @ApiOperation(value = "更新角色权限")
    @PutMapping("/")
    public RespBean update(@RequestParam("rid") Integer id,Integer[] mids){
        menuRoleService.updateByRoleId(id,mids);
        return RespBean.success("更新成功");
    }
}
